package com.fjec.common.eventbus;

import com.fjec.common.Const;
import com.fjec.common.eventbus.event.OpeLogEvent;
import com.fjec.common.eventbus.event.RunTimeLogEvent;
import com.fjec.common.eventbus.event.VisitLogEvent;
import com.fjec.common.util.JsonUtil;
import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.Subscribe;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import java.io.PrintWriter;
import java.io.StringWriter;

@Slf4j
public class LogSubscribe {

    @Subscribe
    @AllowConcurrentEvents
    public void subscribeErrorLogEvent(VisitLogEvent event) {
      /*  if (log.isErrorEnabled()) {
            log.error("subscribeErrorLogEvent -> " + event, event.getThrowable());
        }*/
        if (event.getThrowable() != null) {
            StringWriter sw = new StringWriter();
            event.getThrowable().printStackTrace(new PrintWriter(sw));
            String throwableString = sw.toString();
            event.setThrowable(null);
            event.setThrowableString(throwableString);
            String message = JsonUtil.toJson(event);
            MDC.put(Const.TRACE_ID_KEY, "ERR_LOG");
            log.error("[LOGS]:{}", message);
        } else {
            MDC.put(Const.TRACE_ID_KEY, "VISIT_LOG");
            String message = JsonUtil.toJson(event);
            log.info("[LOGS]:{}", message);
        }
        MDC.remove(Const.TRACE_ID_KEY);
    }

    @Subscribe
    @AllowConcurrentEvents
    public void subscribeRunTimeLogEvent(RunTimeLogEvent event) {
        if (log.isDebugEnabled()) {
            log.debug("subscribeRunTimeLogEvent -> " + event);
        }
    }

    @Subscribe
    @AllowConcurrentEvents
    public void operateLogEvent(OpeLogEvent event) {
        String message = JsonUtil.toJson(event);
        MDC.put(Const.TRACE_ID_KEY, event.getTraceId());
        log.info("[LOGS]:{}", message);
        MDC.remove(Const.TRACE_ID_KEY);
    }
}
